package dao

import (
	"context"
	"time"

	"device-admin/internal/dal"
	"device-admin/internal/models"

	db_sharding "192.168.1.75/go-pkg/db-sharding"
)

type Heatmap struct{}

type HeatmapMap struct {
	MapID   string `json:"map_id" gorm:"column:map_id"`
	MapName string `json:"map_name" gorm:"column:map_name"`
}

// Create 初始热力图数据
func (Heatmap) Create(
	ctx context.Context,
	query *dal.Query,
	robotID string,
	x, y, dir float32,
	mapID string,
	mapName string,
) {
	db := query.DeviceHeatMap.WithContext(ctx).UnderlyingDB()
	dbs := db_sharding.GetDB(ctx, db, models.DeviceHeatMapTpl{}, time.Now().Unix(), time.Now().Unix())
	h := dal.Use(dbs.WriteDB).DeviceHeatMap
	var deviceHeatMap models.DeviceHeatMap
	deviceHeatMap.RobotID = robotID
	deviceHeatMap.PosX = x
	deviceHeatMap.PosY = y
	deviceHeatMap.PosDirection = dir
	deviceHeatMap.MapID = mapID
	deviceHeatMap.MapName = mapName
	deviceHeatMap.CreatedDate = time.Now().Format("2006-01-02")
	deviceHeatMap.CreatedMinute = time.Now().Format("2006-01-02 15:04")
	h.WithContext(ctx).Create(&deviceHeatMap)
}

// MapList 热力图地图列表
func (Heatmap) MapList(ctx context.Context, query *dal.Query, robotID string, startTime, endTime int64) ([]*models.DeviceHeatMap, error) {
	db := query.DeviceHeatMap.WithContext(ctx).UnderlyingDB()
	dbs := db_sharding.GetDB(ctx, db, models.DeviceHeatMapTpl{}, startTime, endTime)
	h := dal.Use(dbs.QueryDB).DeviceHeatMap
	mapList, _ := h.WithContext(ctx).
		Select(h.MapID, h.MapName).
		Where(h.RobotID.Eq(robotID)).
		Where(h.CreatedAt.Between(startTime, endTime)).
		Group(h.MapID).
		Find()
	return mapList, nil
}

// PositionData 热力图数据
func (Heatmap) PositionData(ctx context.Context, query *dal.Query, robotID, mapID string, startTime, endTime int64) ([]*models.DeviceHeatMap, error) {
	db := query.DeviceHeatMap.WithContext(ctx).UnderlyingDB()
	dbs := db_sharding.GetDB(ctx, db, models.DeviceHeatMapTpl{}, startTime, endTime)
	h := dal.Use(dbs.QueryDB).DeviceHeatMap
	deviceHeatMap, _ := h.WithContext(ctx).
		Where(h.RobotID.Eq(robotID)).
		Where(h.CreatedAt.Between(startTime, endTime)).
		Where(h.MapID.Eq(mapID)).
		Find()

	return deviceHeatMap, nil
}
